package cn.appliedata.base.zuul.filter;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;
/**
 * 设置新session到cookie并传递给其它微服务
 * 
 * @author zhengcq
 *
 */
@Slf4j
public class AuthHeaderFilter extends ZuulFilter {

	@Override
	public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpSession session = request.getSession();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
          String cookieValue = "";
          boolean hasCookie = false;
          boolean hasSetCookie = false;
          boolean hasSession = false;
          while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if(name.toUpperCase().equals("COOKIE")) {
            	if(hasCookie) {
            		break;
            	}
            	cookieValue = request.getHeader(name);
                if(cookieValue.toUpperCase().contains("SESSION")) {
                	hasSession = true;
                }
            	hasCookie = true;
            }
            if(name.toUpperCase().equals("SET-COOKIE")) {
            	if(hasSetCookie) {
            		break;
            	}
            	cookieValue = request.getHeader(name);
                if(cookieValue.toUpperCase().contains("SESSION")) {
                	hasSession = true;
                }
                hasSetCookie = true;
            }
          }
          if(!hasSession) {
              ctx.addZuulRequestHeader("cookie", cookieValue + "; SESSION="+session.getId());
              ctx.addZuulResponseHeader("set-cookie", cookieValue + "; SESSION="+session.getId());
              log.info("new session="+ session.getId());
          }
        }
		return null;
	}

	@Override
	public boolean shouldFilter() {
		//是否过滤
		return true;
	}

	@Override
	public int filterOrder() {
		//过滤执行顺序
		return 0;
	}

	@Override
	public String filterType() {
		/*
		pre：路由之前
		routing：路由之时
		post： 路由之后
		error：发送错误调用
		*/
		return FilterConstants.PRE_TYPE;
	}

}
